package com.lemon.utils;

import com.lemon.config.Config;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;

import java.util.HashSet;
import java.util.Set;

/**
 * @Author liuli
 * @Date 2020/10/11 3:05
 */
public class JedisUtil {
    private final static Logger logger = LoggerFactory.getLogger(JedisUtil.class);


    // 其内部进行了池化 无需手动借还 单例模式使用即可
    private static JedisCluster jedisCluster = null;

    public static JedisCluster getJedisCluster() {
        if (jedisCluster == null) {
            synchronized (JedisUtil.class) {
                if (jedisCluster == null) {
                    try {
                        Set<HostAndPort> clusterNodes = new HashSet();
                        String[] nodes = Config.redisCluster.split(",");
                        for (String node : nodes) {
                            String[] addAndport = node.split(":");
                            clusterNodes.add(new HostAndPort(addAndport[0], Integer.parseInt(addAndport[1])));
                        }
                        //初始化common-pool连接池,并设置相关参数
                        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
                        poolConfig.setMaxTotal(Config.maxTotal); // 最大连接数
                        poolConfig.setMaxIdle(Config.maxIdle); // 最大空闲连接数
                        jedisCluster = new JedisCluster(clusterNodes, poolConfig);
                    } catch (Exception e) {
                        logger.error("JedisCluster init error.", e);
                    }
                    return jedisCluster;
                } else {
                    return jedisCluster;
                }
            }
        } else {
            return jedisCluster;
        }
    }
}
